package com.sky.aspect;

import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.globalAnnotation.AutoFill;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    //切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.globalAnnotation.AutoFill)")
    public void autoFillPointCut(){}

    //切面
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("字段自动填充");
        //方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //方法上的注解中的值
        OperationType operationType = autoFill.value();

        //获取方法中的参数
        Object[] args = joinPoint.getArgs();
        Object entity = args[0];//参数对象

        //判断是insert 还是update
        try {
            if(operationType==OperationType.INSERT){
                Method setCreatTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME  , LocalDateTime.class);
                setCreatTime.invoke(entity,LocalDateTime.now());
                Method setupdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME  , LocalDateTime.class);
                setupdateTime.invoke(entity,LocalDateTime.now());

                Method setCreatUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER , Long.class);
                setCreatUser.invoke(entity,BaseContext.getCurrentId());
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER ,Long.class);
                setUpdateUser.invoke(entity,BaseContext.getCurrentId());
                return;
            }
            if(operationType==OperationType.UPDATE){
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER ,Long.class);
                setUpdateUser.invoke(entity,BaseContext.getCurrentId());
                Method setupdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME  , LocalDateTime.class);
                setupdateTime.invoke(entity,LocalDateTime.now());

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
